import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { MenuService } from '../../core/services/menu.service';
import { MapService, StyleService } from '../../core';
import { PollutsService } from './polluts.service';
import * as wellknown from 'wellknown';
import { MainFormatService } from '../../core/services/main-format.service';
import { MapboxDrawService } from '../../core/services/mapbox-draw.service';
import { CoreMessageService } from '../../core/services/core-message.service';
import { LayerManageService } from '../../core/services/layer-manage.service';
@Component({
  selector: 'app-polluts',
  templateUrl: './polluts.component.html',
  styleUrls: ['./polluts.component.scss']
})
export class PollutsComponent implements OnInit, OnDestroy {
  isDrag = false;
  conditionIsShow = null;
  timter = null;
  menuList = null;
  isOpen = false;
  keyValue = null;
  menuItem = null;
  layersList = null;
  treeNodeInfo = null;
  mapboxglmap = null;
  conditionList = null;
  dynamticList = null;
  wktGeom = '';
  pbody = {
    layerId: '',
    propertyParams: '',
    geom: ''
  };
  // table表格
  tabledata = {};
  // 分页卡数据
  pagemsg;
  totalRecord = 0;
  param = {
    pagesize: 5,
    pageindex: 1
  };
  cardIsShow = false;
  dynambody = {
    layerId: '',
    propertyParams: [],
    geom: ''
  };
  pagenNo = 1;
  paramsstr = {
    pageSize: 5,
    pageNo: 1
  };
  listData = null;
  slideCard = true;
  counter = 4;
  hoveredStateId = null;
  closeSelectItem = null;
  // 订阅数组
  subscriptations = [];
  constructor(
    private pollutsService: PollutsService,
    private apboxMapService: MapService,
    private menuService: MenuService,
    private styleMapService: StyleService,
    private mainFormatService: MainFormatService,
    private mapboxDrawService: MapboxDrawService,
    private coreMessageService: CoreMessageService,
    private layerManageService: LayerManageService,
    private activatedRoute: ActivatedRoute,
    private router: Router,
  ) {
    const urlArr = router.url.split("/")
    if (urlArr && urlArr.length > 0) {
      const path = urlArr[urlArr.length - 1];
      this.getSideMenuList(path);
    }
  }
  ngOnInit() {
    // 侧边栏展开！
    this.isOpen = true;
    this.apboxMapService.init().then((mapboxglmap: any) => {
      this.mapboxglmap = mapboxglmap;
      if (mapboxglmap.isStyleLoaded() || this.apboxMapService.styleLoaded) {
        this.mapInit(mapboxglmap);
      } else {
        mapboxglmap.on('load', () => {
          this.mapInit(mapboxglmap);
        });
      }
    });
    this.getLayersList();

    // 关闭二级查询条件面板以及标识绘制的面板以及查询结果列表面版以及识别出来的详情信息框面板！
    this.subscriptations.push(
      postal.channel('TWOLEVEL_PANEL_CHANNEL').subscribe('twolevel-panel', res => {
        this.close(true);
      }),
      postal.channel('DRAW_TOOL_CHANNEL').subscribe('getGeo', res => {
        if (res) {
          this.wktGeom = wellknown.stringify(res.features[0].geometry);
        } else {
          this.wktGeom = '';
        }
      }),
    );
  }
  mapInit(map) {
    this.mapboxDrawService.reset(map);
  }
  close(e) {
    const layers = this.styleMapService.getLayersIDlist();
    this.apboxMapService.removeLayerByIds(layers);
    this.menuItem = null;
    this.cardIsShow = false;
    this.closeSelectItem = {
      isVisible: false
    };
  }
  getSideMenuList(id) {
    this.menuService.getSideMenuList(id).subscribe(res => {
      this.menuList = res;
    });
  }
  layerChnage(e) {
    // this.isOpenLayer = true;
    this.conditionIsShow = { isVisible: true };
    const layers = this.styleMapService.getLayersIDlist();
    this.apboxMapService.removeLayerByIds(layers);
    this.listData = null;
    this.cardIsShow = false;
    if (this.treeNodeInfo) {
      this.getPropertyList();
      setTimeout(() => {
        // this.exeSearchProperty();
      }, 300);
    }
    // 每次切换图层，更新地图zoom。
    this.mapboxglmap.zoomTo(13);
  }
  getPropertyList() {
    const params = {
      layerId: this.treeNodeInfo,
    };
    this.pollutsService.getPropertyInfo(params).subscribe(res => {
      if (res.code === 1 && res.data.conditions) {
        this.conditionList = res.data.conditions;
      } else {
        this.conditionList = null;
      }
    });
  }
  queryInfo(obj) {
    this.pagenNo = 1;
    this.dynamticList = [];
    obj.forEach(element => {
      if (element.value !== null) {
        this.dynamticList.push(element);
      }
    });
    this.exeSearchProperty();
    this.exeSearchGoemetry();
  }
  // 属性查询
  exeSearchProperty() {
    Object.assign(this.dynambody, {
      layerId: this.treeNodeInfo,
      propertyParams: this.dynamticList || [],
      geom: this.wktGeom
    });
    Object.assign(this.paramsstr, {
      pageNo: this.pagenNo
    });
    this.pollutsService.dynamicuQeryProperty(this.paramsstr, this.dynambody).subscribe(res => {
      if (res.code === 1 && res.data.list) {
        const list = res.data.list;
        list.forEach(element => {
          element.detail = JSON.parse(element.detail);
        });
        this.listData = list;
        this.totalRecord = res.data.totalRecord;
        this.cardIsShow = true;
        this.slideCard = true;
      } else {
        this.listData = null;
        this.cardIsShow = false;
        this.slideCard = false;
      }

      // 绘制circle
    });
  }
  // 选中列表项 定位
  searchListItemClick(item) {
    this.layerManageService.fitPositionAddLayer(this.mapboxglmap, item, 'hightlight', '', false);
    clearInterval(this.timter);
    this.timter = setInterval(() => {
      this.changeLineColor();
    }, 100);
  }

  changeLineColor() {
    const steps = 18;
    if (this.counter < steps) {
      if (this.mapboxglmap.getLayer('highlightLineID')) {
        this.mapboxglmap.setPaintProperty('highlightLineID', 'line-width', this.counter);
      }
    } else {
      this.counter = 4;
    }
    this.counter += 2;
  }
  // 分页绘制
  search() { }
  getSideMenuItem(item) {
    this.clearData();
    this.menuItem = item;
    if (item.visible) {
      if (item.data.type) {
        this.getLayerRainList({ type: item.data.type });
      } else {
        this.getLayersList();
      }
    } else {
      this.clearLayerAndCard();
    }
  }
  clearLayerAndCard() {
    const layers = this.styleMapService.getLayersIDlist();
    this.apboxMapService.removeLayerByIds(layers);
    this.cardIsShow = false;
  }
  getLayersList() {
    this.pollutsService.getLayersList().subscribe(res => {
      if (res.code === 1 && res.data) {
        this.layersList = res.data;
        this.treeNodeInfo = res.data[0].layerid;
        this.getPropertyList();
      } else {
        this.layersList = null;
      }
    });
  }
  getLayerRainList(param) {
    this.pollutsService.getLayersRainList(param).subscribe(res => {
      if (res.code === 1 && res.data) {
        this.layersList = this.mainFormatService.fieldAdaptive(res.data, [['shortname', 'layername']]);
        this.treeNodeInfo = res.data[0].layerid;
        this.getPropertyList();
      } else {
        this.layersList = null;
      }
    });
  }
  // 空间位置信息查询
  exeSearchGoemetry() {
    Object.assign(this.pbody, {
      layerId: this.treeNodeInfo,
      propertyParams: this.dynamticList || [],
      geom: this.wktGeom
    });
    this.pollutsService.queryGeometry(this.pbody).subscribe(res => {
      if (res.code === 1 && res.data) {
        this.styleMapService.drawGeo(res.data);
      }
    });
  }
  // 页数改变时！
  pageIndexChange() {
    // 属性查询
    this.exeSearchProperty();
  }
  controllCard(e) {
    if (e === 'slide') {
      this.slideCard = !this.slideCard;
    } else if (e === 'move') {
      // this.isDrag = !this.isDrag;
    } else {
      const removelayer = ['highlightLineID', 'geo.ami.diffus'];
      this.apboxMapService.removeLayerByIds(removelayer);
      this.cardIsShow = !this.cardIsShow;
      // clearInterval(this.timter);
    }
  }
  clearData() {
    // 清理掉geometry！
    this.wktGeom = '';
    // 设置框选、圈选、多边选为默认项
    this.coreMessageService.clearAll();
    // 移除图层
    this.removeLayers();
    this.cardIsShow = false;
  }
  removeLayers() {
    const layers = this.styleMapService.getLayersIDlist();
    this.apboxMapService.removeLayerByIds(layers);
  }
  removeAnimaLayer(e) {
    const layers = this.styleMapService.getAnimationsIDlist();
    this.apboxMapService.removeLayerByIds(layers);
  }
  ngOnDestroy() {
    this.removeLayers();
    this.isOpen = false;
    clearInterval(this.timter);
    // 取消订阅
    this.subscriptations.forEach(element => {
      element.unsubscribe();
    });
  }
}
